//
//  EncryptService.m
//  IPDirectConnection
//
//  Created by lianglibao on 2019/4/23.
//  Copyright © 2019 lianglibao. All rights reserved.
//

#import "EncryptService.h"
#import <CommonCrypto/CommonDigest.h>

@implementation EncryptService
+ (NSString *)signCreatWithParam:(NSDictionary *)param {
    NSString *sign = nil;
    
    NSArray *keys = param.allKeys;
    
    keys = [keys sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
        
        return [obj1 compare:obj2];
    }];
    
    NSMutableString *paramString = [NSMutableString stringWithCapacity:10];
    for (NSString *key in keys) {
        
        [paramString appendFormat:@"%@%@", key, param[key]];
    }
    
    NSString *signKey = singinKey();
    [paramString appendString:signKey];
    
    sign = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef)SHA256(paramString),
                                                                                 NULL,
                                                                                 (CFStringRef) @"!*'();:@&=+$,%#[]",
                                                                                 kCFStringEncodingUTF8));
    
    return sign;
}

static inline NSString *SHA256(NSString *para) {
    const char *s = [para cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];
    
    uint8_t digest[CC_SHA256_DIGEST_LENGTH] = { 0 };
    CC_SHA256(keyData.bytes, (CC_LONG)keyData.length, digest);
    NSData *outData = [NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
    NSString *hash = [outData description];
    hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
    hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
    hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
    return hash;
}

static inline NSString *singinKey() {
#if TARGET_IPHONE_SIMULATOR
    return @"";
#else
    return @"";
#endif
}

@end
